<template>
  <!-- <div>领取用户列表</div> -->

  <div class="shop">
    <div class="top">
      <div style="display:inline-block;width:500px">
        <span>优惠券面额：{{ datalist.amount }}， 总发行：{{ datalist.voucherQuantity }}张，每人限领数量：{{ datalist.voucherGrant
          }}张，</span>
        <br />
        <span>券使用有效周期：{{ datalist.useEndTime }} 至 {{ datalist.useStartTime }}</span>
      </div>
      <el-button class="search" size="small" @click="goBack">返回上一页</el-button>
      <el-button class="search" size="small" type="primary" @click="searchCategoryData">搜索</el-button>

      <!-- <el-input
          class="search input"
          size="small"
          v-model="form.productNo"
          placeholder="输入id查询"
          clearable
        ></el-input> -->
      <el-input class="search input" size="small" v-model="form.keyword" placeholder="输入商品名称查询" clearable></el-input>
    </div>

    <el-table :key="tableKey" :data="tableData" style="width:100%" max-height="680" :cell-style="tc"
      :header-cell-style="tccolor">
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="商品ID" prop="id"></el-table-column>
      <el-table-column label="商品名称" prop="title"></el-table-column>
      <el-table-column label="商品图片" prop="relation_product_count">
        <template slot-scope="scope">
          <span><img :src="scope.row.listImgUrl" style="width:80px;cursor:pointer;"
              @click="viewPic(scope.row)" /></span>
        </template>
        <!-- <template slot-scope="scope">
            <div class="img">
              <img
                :key="scope.row.ID"
                style="width:100px;"
                :src="scope.row.pic_url? scope.row.pic_url : errorImg"
                alt
              />
            </div>
          </template> -->
      </el-table-column>
      <el-table-column align="left" label="分类1">
        <template slot-scope="scope">
          <span v-if="scope.row.parentCateId > 0">{{ scope.row.parentCateName }}<span v-if="scope.row.cateId > 0">-{{
            scope.row.cateName }}</span><span v-if="scope.row.thirdCateId > 0">-{{ scope.row.thirdCateName
              }}</span></span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="分类2">
        <template slot-scope="scope">
          <span v-if="scope.row.parentCateId2 > 0">{{ scope.row.parentCateName2 }}<span v-if="scope.row.cateId2 > 0">-{{
            scope.row.cateName2 }}</span><span v-if="scope.row.thirdCateId2 > 0">-{{ scope.row.thirdCateName2
              }}</span></span>
        </template>
      </el-table-column>
      <el-table-column width="100" align="right" label="供货成本" sortable="custom" prop="min_supply_price">
        <template slot-scope="scope">
          <span>￥{{ scope.row.minSupplyPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100" align="right" label="售价" sortable="custom" prop="min_sale_price">
        <template slot-scope="scope">
          <span>￥{{ scope.row.minSalePrice }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100" align="right" label="抵扣" sortable="custom" prop="redpacket">
        <template slot-scope="scope">
          <span>{{ scope.row.redpacket }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" prop="id">
          <template slot-scope="scope">
            <p v-if="scope.row.on_sale==1">审核中</p>
            <p v-if="scope.row.on_sale==5">售卖中</p>
            <p v-if="scope.row.on_sale==10">驳回</p>
            <p v-if="scope.row.on_sale==15">下架</p>
          </template>
        </el-table-column> -->
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" v-if="scope.row.isCheck == 0"
            @click="handleSettle(scope.row)">选择</el-button>
          <el-button type="success" size="mini" v-else @click="handleIn(scope.row)">取消选择</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24">
      <!-- <div class="bottomBtn">
        <el-button size="small" type="primary" @click="removeShop()">移除当前页选中商品</el-button>
      </div> -->

      <div class="bottomBtn" style="padding-left: 20px;">
        <el-button size="small" type="primary" @click="selectAllProducts()">本页全加入</el-button>
      </div>
      <div class="bottomBtn" style="padding-left: 20px;">
        <el-button size="small" type="primary" @click="selectProducts()">选中商品加入优惠券</el-button>
      </div>
      <div class="bottomBtn" style="padding-left: 20px;">
        <el-button size="small" type="primary" @click="submit()">确定提交</el-button>
      </div>
      <div class="pagination">
        <el-pagination background @current-change="pageChange" :current-page="form.pageNum" :page-size="form.pageSize"
          layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </el-col>
  </div>
</template>


<script>
//   import { CouponRelevanceShopList,isShopCouponChange } from "@/api/autarky";
import {
  product_list,
  product_delete,
  product_update_order,
  product_detail,
  product_update_stock,
  product_up,
  product_down,
  product_category,
  product_sync,
  productExport,
  product_recovery
} from '../../api/product';
import { cashCouponDetail, updateBindsProduct } from '@/api/store'
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';
export default {
  data() {
    return {
      tableKey: 0,
      selectProduct: [],
      datalist: {},
      isShowAddCategory: false,
      coupon_id: "",
      selectedItems: [],
      form: {
        keyword: "",
        pageNum: 1,
        pageSize: 20,
        status: 0,
        pageNum: 1,
        auditStatus: 3,
        getSaleCount: 1,
        isPackage: 0,
        isCard: 0,
        cardType: 0,
        productNo: undefined
      },
      errorImg: '',
      total: 0,
      tableData: []
    };
  },
  mounted() {
    let data = this.$route.query.datalist;
    console.log(data, '11111111111111')
    // this.datalist = Object.assign({}, data);
    this.form.coupon_id = data;
    this.getCouponDetail()
    this.getsCouponRelevanceShopListData();
    // this.getCouponProduct()
  },
  methods: {
    async submit() {
      console.log(this.selectProduct, this.datalist.id)
      let query = {
        productIds: this.selectProduct.join(","),
        status: 1
      }
      let res = await updateBindsProduct(query, this.datalist.id);
      if (res.code === 200) {
        // this.datalist = res.data;
        // console.log(res.data)
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
      }
    },
    selectAllProducts() {
      this.tableData.forEach(item => {
        item.isCheck = 1
      })
      this.tableKey += 1
      this.tableData.map(item => {
        this.selectedItems.push(item.id);
      });
    },
    handleSelectionRowChange(e) {
      console.log(e, '############')
    },
    handleSettle(row) {
      let i = this.tableData.findIndex(it => it.id == row.id)
      let j = this.selectProduct.findIndex(it => it == row.id)
      if (j == -1) {
        this.selectProduct.push(row.id)
      }
      if (i !== -1) {
        this.tableData[i].isCheck = 1
      }
      this.tableData = this.tableData
      this.tableKey += 1;
      console.log(this.selectProduct)
    },
    handleIn(row) {
      let i = this.tableData.findIndex(it => it.id == row.id)
      if (i !== -1) {
        this.tableData[i].isCheck = 0
      }
      let j = this.selectProduct.findIndex(it => it == row.id)
      if (j !== -1) {
        this.selectProduct.splice(j, 1)
      }
      this.tableData = this.tableData
      this.tableKey += 1;
      console.log(this.selectProduct)
    },
    selectProducts() {
      let i = 0
      // if (this.selectProduct.length) {
      //   for (let j = 0; j < this.selectProduct.length; j++) {
      //     i = this.selectedItems.findIndex(it => it == this.selectProduct[j])
      //     console.log(i)
      //     if (i !== -1) {
      //       this.selectedItems.splice(i, 1)
      //     }
      //   }
      // }
      // for(let i = 0; i < this.selectProduct.length; i++){

      //   // for(let j = 0; j < this.tableData.length; j++){
      //   //   if(this.selectedItems[i].id == this.tableData[j].id){
      //   //     this.tableData.splice(j,1)
      //   //   }
      //   // }
      // }
      this.selectProduct = this.selectProduct.concat(this.selectedItems)

      // this.uniqueArrayByProperty(this.selectProduct)
      this.selectProduct = this.uniqueArray(this.selectProduct);
      console.log(this.selectProduct)
    },
    uniqueArray(arr) {
      return arr.filter((item, index) => arr.indexOf(item) === index);
    },
    viewPic(row) {
      if (row.imgUrls) {
        let all_pic = row.imgUrls.split(",");
        $("#pic_viewer").html("");
        if (all_pic && all_pic.length > 0) {
          all_pic.forEach((item, idx) => {
            var str = '<li style="width:100%;">';
            str += '<img rel-src="' + item + '" src="' + item + '">';
            str += '</li>';
            $("#pic_viewer").append(str);
          })
        }
        this.viewerId && this.viewerId.destroy()
        this.viewerId = new Viewer(document.getElementById('pic_viewer'));
        $('#pic_viewer').find("img").eq(0).trigger("click")
      }
    },
    async getCouponProduct() {
      let res = await updateBindsProduct([], this.form.coupon_id);
      if (res.code === 200) {
        this.datalist = res.data;
        console.log(res.data)

      } else {
        this.$message.error(res.message);
      }
    },
    async getCouponDetail() {
      let res = await cashCouponDetail(this.form.coupon_id);
      if (res.code === 200) {
        this.datalist = res.data;
        console.log(res.data)

      } else {
        this.$message.error(res.message);
      }
    },
    //搜索数据
    searchCategoryData() {
      this.getsCouponRelevanceShopListData();
    },
    pageChange(page) {
      this.form.pageNum = page;
      //获取更多数据
      this.getsCouponRelevanceShopListData();
    },
    //获取优惠券列表数据
    async getsCouponRelevanceShopListData() {
      let res = await product_list(this.form);
      if (res.code === 200) {
        this.tableData = res.data.list;
        this.tableData.forEach(item => {
          let i = this.selectProduct.findIndex(it => it == item.id)
          if (i !== -1) {
            this.tableData[i].isCheck = 1
          } else {
            item.isCheck = 0
          }

        });
        this.selectProduct


        this.total = res.data.total;
      } else {
        this.$message.error(res.message);
      }
    },
    // 全选
    handleSelectionChange(value) {
      this.selectedItems = [];
      console.log(value, '1111');

      value.map(item => {
        this.selectedItems.push(item.id);
      });
      if (value.length) {
        this.selectedItems.forEach(item => {
          let i = this.tableData.findIndex(it => it.id == item)
          if (i !== -1) {
            this.tableData[i].isCheck = 1
            // this.tableKey += 1
          }
        });
      } else {
        this.tableData.forEach(item => {
          item.isCheck = 0
        })
        // this.tableKey += 1
        console.log(value, '2222');
      }

    },
    // 上一页
    goBack() {
      this.$router.go(-1);
    },
    removeShop() {
      let coupon_ids = [];
      coupon_ids.push(this.datalist.id)
      const params = {
        coupon_ids: coupon_ids,
        del_relates: this.selectedItems.join(",")
      };
      console.log(params);
      isShopCouponChange(params).then(res => {
        if (res.code === 10000) {
          this.$message.success("移除商品成功");
          this.getsCouponRelevanceShopListData();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    }
  }
};
</script>

<style lang="scss" scoped>
.shop {
  padding: 20px;

  .top {
    margin-bottom: 20px;

    .search {
      float: right;
      margin-left: 12px;
    }

    .input {
      width: 150px;
    }
  }

  .cetain {
    color: #f4222d;
  }

  .pagination {
    float: right;
    margin-top: 12px;
  }

  .icon_cate {
    float: left;
  }

  .demo-ruleForm {
    padding: 20px;
  }

  .note {
    color: #666666;
    font-size: 14px;
    margin-top: 28px;
  }

  .align {
    text-align: center;
    margin-bottom: 20px;
  }
}

.bottomBtn {
  display: inline-block;
  position: relative;
  top: 12px;
}
</style>
